<template>
    <div>
        <!-- 租客入住 -->
        <Modal
            v-model="isModalVisible"
            :closable="false"
            :mask-closable="false"
            :loading="true"
            :title="isFrozen ? '租客解冻': '租客冻结'"
            width="640">

            <Form ref="checkInForm" :label-width="120"
            style="height: 100%;">
                <Row class="renter-list-info margin-bot-16">
                    <Col span="4" class="info-title">租客姓名：</Col>
                    <Col span="9">{{renter.name || '-' }}</Col>
                </Row>
                <Row class="renter-list-info margin-bot-16">
                    <Col span="4" class="info-title">手机号码：</Col>
                    <Col span="7">{{renter.phone || '-'}}</Col>
                </Row>

                <Row class="renter-list-info margin-bot-5" type="flex" align="middle">
                    <Col span="4" class="info-title">房间地址：</Col>
                    <Col span="9">{{lease.home_address}}</Col>
                </Row>
                <Row class="renter-list-info margin-bot-5" type="flex" align="middle">
                    <Col span="4" class="info-title">房间名称：</Col>
                    <Col span="7">{{lease.room_name}}</Col>
                </Row>

                <div class="split-line" v-if="lease.co_tenants.length"></div>
                <Row class="renter-list-cells margin-bot-5" v-for="(item,index) in lease.co_tenants" :key="index">
                    <Col span="4" style="text-align:right">同租人：</Col>
                    <Col span="3">{{item.name }}</Col>
                    <Col span="3" style="text-align:right">电话：</Col>
                    <Col span="3">{{item.phone}}</Col>
                    <Col span="4" style="text-align:right">关系：</Col>
                    <Col span="7">{{item.co_tenant_lease && item.co_tenant_lease.relationship}}</Col>
                </Row>

                <div class="split-line"></div>

                <FormItem label="租约有效期：" class="margin-bot-5">
                    <span>{{new Date(lease.lease_range[0]).Format('yyyy-MM-dd HH:mm')}} - </span>
                    <span>{{new Date(lease.lease_range[1]).Format('yyyy-MM-dd HH:mm')}}</span>                
                </FormItem>

                <div class="split-line"></div>

                <!-- <Row class="renter-list-info" type="flex" align="middle">
                    <Col span="4" style="text-align:right;">门禁：</Col>
                    <Col span="6">暂无</Col>
                    <Col span="14">
                        <Checkbox style="margin-left:10px" :disabled="!hasAccessControl" v-model="frozenDoor" v-if="!isFrozen"> 冻结门禁卡</Checkbox>
                        <Checkbox style="margin-left:10px" :disabled="!hasAccessControl" v-model="frozenDoor" v-if="isFrozen"> 恢复门禁卡生效</Checkbox>
                    </Col>
                </Row> -->

                <Row class="renter-list-info" type="flex" align="middle">
                    <Col span="4" class="info-title">开门授权：</Col>
                    <Col span="10">
                        <Checkbox v-model="isFroOrUnFroPassword" style="padding-left: 15px;" :disabled="isNoGatewayLock">{{isFrozen ? '恢复' : '冻结'}}租客, 租客相关的授权状态同步</Checkbox>
                    </Col>
                </Row>

                <!-- <FormItem label="密码有效期：" class="margin-bot-5">
                    <span>{{new Date(lease.lease_range[0]).Format('yyyy-MM-dd HH:mm')}} - </span>
                    <span>{{new Date(lease.lease_range[1]).Format('yyyy-MM-dd HH:mm')}}</span>                
                </FormItem> -->

                <div class="split-line"></div>

                <FormItem v-if="overdraft && hasElemeter" label="当前电表读数：" class="margin-bot-5">
                    {{roomInfo.electric_read || 0}} KWH （更新于 {{new Date(roomInfo.updated_at || Date.now()).Format('yyyy/MM/dd')}}）
                </FormItem>
                <FormItem v-if="!overdraft && hasElemeter" label="当前剩余电量：" class="margin-bot-5">
                    {{ leftElectric }} KWH （更新于 {{new Date(roomInfo.updated_at || Date.now()).Format('yyyy/MM/dd')}}）
                </FormItem>
            </Form>

            <div slot="footer">
                <Button type="ghost" size="large" @click="cancelContinue('checkInForm')">取消</Button>
                <Button type="primary" :loading="pending" size="large" @click="handleClick('checkInForm')">{{isFrozen ? '解冻': '冻结'}}</Button>
            </div>
        </Modal>

        <Modal v-model="isShowPasswordModal && !!this.passwordDetail.length" :title="`${this.isFrozen ? '解冻': '冻结'}门锁密码`"  width="740" :closable="false" :mask-closable="false">
            <Row v-for="(item, index) in this.passwordDetail" :key="index" >
                <p style="text-align: center; font-size: 20px;">{{item.name === 'room' ? '房间' : '公区'}}门锁密码{{isFrozen ? '解冻': '冻结'}}指令{{item.result === 'ok' ? '成功,请去门锁授权列表里面检查相应的密码状态' : '失败,请去门锁授权列表里面对相应的密码进行操作'}}</p>

                <br>

                <p v-if="item.activation_password_ids" v-for="(id, index) in item.activation_password_ids" :key="index">离线密码{{id}}当天下发，为保障安全，请于次日操作</p>

                <Row v-if="item.unable_batch_operate_pwds">
                    <p>{{item.name === 'room' ? '房间' : '公区'}}门锁版本过低，无法批量删除密码</p>
                    <p>为保障安全，请在{{item.name === 'room' ? '房间' : '公区'}}门锁授权列表中对下列密码进行操作</p>
                    <br/>

                   <Table :columns="columns" :data="item.unable_batch_operate_pwds"></Table>
                </Row>
                <br/>
            </Row>

            <div slot="footer">
                <Button type="ghost" size="large" @click="ok">确定</Button>
            </div>
        </Modal>

        <operateResultModal v-if="isResultModalVisible" @confirm="closeOutModal" :operateResult="operateResult" :operateResultMulti="operateResultMulti"></operateResultModal>
    </div>

    
</template>

<script>
// import validate from '@/libs/validate';
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import { DeviceTypeEnum } from '@/libs/const'
import operateResultModal from './operateResultModal'

export default {
  props: {
    renterId: {
      // 租客Id,必须
      required: true
    },
    lease: {
      // 租赁房间信息
      type: Object,
      required: true
    }
  },
  components: {
    operateResultModal
  },
  data () {
    return {
      columns: [
        {
          title: '授权编号',
          align: 'center',
          key: 'paas_password_id'
        },
        {
          title: '状态',
          align: 'center',
          key: 'pwd_state',
          render: (h, params) => {
            const {
              row: { pwd_state }
            } = params
            return h('span', util.getPasswordStatus(pwd_state))
          }
        },
        {
          title: '被授权人信息',
          align: 'center',
          key: 'name',
          render: (h, params) => {
            const {
              row: { name, send_to }
            } = params
            return h('span', name + ' ' + send_to)
          }
        },
        {
          title: '关联租客',
          align: 'center',
          key: 'tenant_name'
        }
      ],
      isShowPasswordModal: false,
      passwordDetail: [],
      isFroOrUnFroPassword: true,
      renter: {},
      roomInfo: {}, // 具体房间信息
      parentRoomInfo: {},
      passwordType: 0, // 是否授权密码
      frozenDoor: false,
      passwords: '',
      passwordFinishCount: 0, // 冻结密码成功计数
      options3: {
        disabledDate: date => {
          return date && date.valueOf() < new Date(this.lease.lease_range[1]).valueOf()
        }
      },
      pending: false,

      isModalVisible: true,
      isResultModalVisible: false,
      operateResult: [],
      operateResultMulti: null // 一个接口返回多个状态的情况
    }
  },
  created () {
    this.getRoomInfo(this.lease.room_id)
    this.getRenterInfo()
  },
  computed: {
    isNoGatewayLock () {
      if (this.roomInfo && this.roomInfo.devices && this.roomInfo.devices.some((item) => (item.device_type === DeviceTypeEnum.LOCK && item.parent === 'GOD'))) {
        this.isFroOrUnFroPassword = false
        return true
      } else {
        return false
      }
    },

    /**
        * 是否是指纹锁
        */
    isFingerLock () {
      if (this.roomInfo && this.roomInfo.devices && this.roomInfo.devices.some((device) => (device.device_ability.includes('LOCK') && device.model && device.model === 'lk-19'))) {
        return true
      } else {
        return false
      }
    },

    overdraft () {
      // 计算房间是否是后付费
      return this.roomInfo.pay_type === 2
    },
    leftElectric () {
      if (!this.roomInfo.electric_read) {
        return 0
      }
      return util.getLeftElectric(this.roomInfo)
    },
    isFrozen () {
      return this.lease.op_status !== 1
    },

    hasElemeter () {
      let selfHas // 本房间是否有设备
      if (this.roomInfo.devices) {
        selfHas = this.roomInfo.devices.some(item => {
          return item.device_type === DeviceTypeEnum.ELEMETER
        })
      }
      return selfHas // 房间有电表才显示电表相关
    },
    hasAccessControl () {
      return false
    }
  },
  methods: {
    ok () {
      this.isShowPasswordModal = false
      this.isResultModalVisible = true
    },

    resetForm (name) {
      this.$refs[name].resetFields()
    },

    getRenterInfo () {
      http.request(this, api.tenant_info, [this.renterId], null, res => {
        if (res) {
          // 获取到租客信息
          this.renter = res
        }
      })
    },

    frozenOrUnfrozenLease () {
      let finalApi = this.isFrozen ? api.tenant_unfrozen : api.tenant_frozen
      this.operateResult.push({
        params: [finalApi, [this.lease.id], null],
        title: this.isFrozen ? '解冻租赁记录' : '冻结租赁记录'
      })
    },

    frozenOrUnfrozenPassword () {
      let finalApi = this.isFrozen ? api.lease_password_unfrozen : api.lease_password_frozen
      http.request(this, finalApi, [this.lease.id], null, (res, error) => {
        if (error) {
          return
        }

        this.passwordDetail = []
        Object.keys(res).forEach((key) => {
          this.constructData(key, res[key])
        })

        this.isModalVisible = false
        this.isShowPasswordModal = true

        if (!this.passwordDetail.length) { // 如果房间和公区都没有门锁直接删除
          this.ok()
        }
      })
      // this.operateResult.push({
      //     params: [finalApi, [this.lease.id], null],
      //     title: this.isFrozen ? '解冻开门密码' : '冻结开门密码'
      // });
    },

    /**
        * 构造门锁返回的密码列表
        */
    constructData (key, password) {
      this.passwordDetail.push({name: key, ...password})
    },

    handleClick () {
      if (this.isFroOrUnFroPassword) {
        this.frozenOrUnfrozenPassword()
      }

      if (this.isFingerLock) { // 如果是指纹锁
        http.request(this, api.leases_grant_record, [this.lease.id], null, (res, error) => {
          if (error || !res) {
            return
          }

          let pos = false
          res.forEach((room) => {
            if (room.passwords && room.passwords.some((password) => (password.type === 2))) {
              pos = true
            }
          })

          if (pos) { // 如果存在指纹密码调用冻结
            this.frozenOrUnfrozenFingerPassword()
          }
        })
      }
      this.frozenOrUnfrozenLease()

      if (!this.isFroOrUnFroPassword) {
        this.isResultModalVisible = true
      }
    },

    /**
         * 冻结或者解冻指纹密码
         * @param {Boolean} flag true为冻结，false为解冻
         */
    frozenOrUnfrozenFingerPassword () {
      const flag = !this.isFrozen
      const requestApi = flag ? api.finger_password_frozen_mutil : api.finger_password_unfrozen_mutil

      const title = flag ? '冻结开门指纹' : '解冻开门指纹'
      const obj = {
        params: [requestApi, [this.lease.id], null],
        specialTitle: title
      }

      this.operateResultMulti = obj
    },

    closeOutModal () {
      this.$emit('frozenSuccess')
    },

    cancelContinue () {
      this.$emit('cancelContinue')
    },

    getRoomInfo (roomId) {
      // 获取房间具体信息
      if (!roomId) {
        return
      }
      http.request(this, api.room_info, [roomId], null, res => {
        if (res) {
          this.roomInfo = res
        }
      })
    }
  }
}
</script>

<style lang="less">
.font-bold {
    font-weight: bold;
}
</style>
<style lang="less" scoped>
    .info-title {
        text-align:right;
        width:120px;
        padding-right:22px;
    }
</style>